import { asyncRoutes, constantRoutes } from '@/router'
import { deepClone, getUserRoutes } from '@/utils'
import { getSession, getUserInfo } from '@/utils/auth'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit,state }, roles) {
    return new Promise(resolve => {
      let accessedRoutes = asyncRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }

      const userInfo = getUserInfo()
      let _ar = []
      if(typeof(userInfo) == 'string' && userInfo.length>0){
        _ar = JSON.parse(JSON.parse(userInfo).U_Menu).role
      }
      //console.log('userInfo---------',_ar)

      //_ar = ['A1','B1','C1','C2','C3','D1','D2','D3','E1','E2','E3','F1','F2','F3','G1','G2','G3']
      let _arks = [...new Set(_ar.map(v=>v.substr(0,1)))]
      //console.log('generateRoutes-0---------',roles[0],_ar)
      let _accessedRoutes = []
      accessedRoutes.map(v=>{
        if(_arks.indexOf(v.key) >=0 ){
          let _v = v
          const _children = _v.children.filter(item=>_ar.indexOf(item.key)>=0)
          _v.children = _children
          //console.log('generateRoutes-00---------',_v.key, _v.children)
          _accessedRoutes.push(_v)
        }
      })
      //console.log('generateRoutes-1---------',_accessedRoutes)

      commit('SET_ROUTES', _accessedRoutes)
      //console.log('generateRoutes-2---------',state.routes)
      resolve(_accessedRoutes)
    })
  },
  
  getUserRoutes({ commit, state }){
    return new Promise((resolve, reject) => {
        resolve(state.routes)
      }).catch(error => {
        reject(error)
      })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
